package com.zhida.jiyangcenter.order

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.manager.app
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.MainActivity
import com.zhida.jiyangcenter.setting.SetPayPasswordActivity
import com.zhida.jiyangcenter.utils.AliPay
import com.zhida.jiyangcenter.utils.SP
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.SmoothCheckBox
import com.zhida.jiyangcenter.wxapi.WXPayEntryActivity
import kotlinx.android.synthetic.main.activity_pay_order.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@TitleBar(false)
@ContentLayout(R.layout.activity_pay_order)
class PayOrderActivity : BaseActivity() {
    var fragment: PayFragmentDialog? = null
    val adapter = Adapter()
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.title("提交订单")
        rv_pay_order.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_pay_order.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context).sizeResId(R.dimen.dividerSmall)
                .colorResId(R.color.colorBack).build()
        )
        rv_pay_order.adapter = adapter
        adapter.setOnItemClickListener { _, _, position ->
            adapter.position = position
            adapter.notifyDataSetChanged()
        }
        tv_pay_money.text = "￥${intent.getDoubleExtra("total_money", 0.00)}"
        tv_pay_order.setOnClickListener {
            when (adapter.position) {
                -1 -> {
                    toast("请选择支付方式")
                }
//                0 -> {
//                    lifecycleScope.request({ APIAccount.service().personalInfo() },
//                        object : BaseAPI<PersonalInfoEntity>() {
//                            override fun onSuccess(
//                                t: PersonalInfoEntity?,
//                                state: Int,
//                                msg: String
//                            ) {
//                                if (t?.pay_password == true) {
//                                    SP.PayOrderUuid.put(intent.getStringExtra("orderCode") ?: "")
//                                    SP.PayType.put(intent.getStringExtra("kind") ?: "")
//                                    fragment = PayFragmentDialog()
//                                    fragment?.arguments = Bundle().apply {
//                                        putString("code", intent.getStringExtra("orderCode") ?: "")
//                                        putString("kind", intent.getStringExtra("kind") ?: "")
//                                    }
//                                    fragment?.setListner {
//                                        val intent = Intent(
//                                            this@PayOrderActivity,
//                                            PaySuccessActivity::class.java
//                                        ).apply {
//                                            putExtra("PayOrderUuid", SP.PayOrderUuid.get())
//                                            putExtra("PayOrderType", SP.PayType.get())
//                                            putExtra(
//                                                "PayMoney",
//                                                intent.getDoubleExtra("total_money", 0.00)
//                                            )
//                                            putExtra("PayType", adapter.position)
//                                        }
//                                        startActivity(intent)
//                                        for (i in app.activityStack.size - 1 downTo 0) {
//                                            if (app.activityStack[i] !is MainActivity) {
//                                                app.activityStack[i].finish()
//                                            }
//                                        }
//                                        finish()
//                                    }
//                                    fragment?.show(supportFragmentManager, "pay")
//                                } else {
//                                    startActivity<SetPayPasswordActivity> {
//                                        putExtra("type", "add")
//                                    }
//                                }
//                            }
//
//                            override fun onError(e: APIException) {
//                                tipFail(e.eMessage)
//                            }
//
//                        })
//                }
                0 -> {
                    lifecycleScope.request({
                        APIPay.service().wxpay(
                            intent.getStringExtra("orderCode") ?: "",
                            intent.getStringExtra("kind") ?: ""
                        )
                    }, object : BaseAPI<WechatEntity>() {
                        override fun onSuccess(response: WechatEntity?, state: Int, msg: String) {
                            WXPayEntryActivity.setWxPay {
                                lifecycleScope.launch(Dispatchers.Main) {
                                    val intent = Intent(
                                        this@PayOrderActivity,
                                        PaySuccessActivity::class.java
                                    ).apply {
                                        putExtra("PayOrderUuid", SP.PayOrderUuid.get())
                                        putExtra("PayOrderType", SP.PayType.get())
                                        putExtra(
                                            "PayMoney",
                                            intent.getDoubleExtra("total_money", 0.00)
                                        )
                                        putExtra("PayType", adapter.position)
                                    }
                                    startActivity(intent)
                                    for (i in app.activityStack.size - 1 downTo 0) {
                                        if (app.activityStack[i] !is MainActivity) {
                                            app.activityStack[i].finish()
                                        }
                                    }
                                    finish()
                                }
                            }
                            SP.PayOrderUuid.put(intent.getStringExtra("orderCode") ?: "")
                            SP.PayType.put(intent.getStringExtra("kind") ?: "")
                            wechatRecharge(
                                response?.appid,
                                response?.noncestr,
                                response?.`package`,
                                response?.partnerid,
                                response?.prepayid,
                                response?.sign,
                                response?.timestamp
                            )
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                    })
                }
                1 -> {
                    lifecycleScope.request({
                        APIPay.service().alipay(
                            intent.getStringExtra("orderCode") ?: "",
                            intent.getStringExtra("kind") ?: ""
                        )
                    }, object : BaseAPI<AlipayEntity>() {
                        override fun onSuccess(t: AlipayEntity?, state: Int, msg: String) {
                            SP.PayOrderUuid.put(intent.getStringExtra("orderCode") ?: "")
                            SP.PayType.put(intent.getStringExtra("kind") ?: "")
                            AliPay(activity).pay(
                                t?.order_string ?: "",
                                intent.getStringExtra("kind") ?: "",
                                intent.getStringExtra("orderCode") ?: "",
                                intent.getDoubleExtra("total_money", 0.00),
                                adapter.position
                            )
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                    })
                }
            }

        }
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.request(
            { APIMemberApps.service().balance() },
            object : BaseAPI<BalanceEntity>() {
                override fun onSuccess(t: BalanceEntity?, state: Int, msg: String) {
                    adapter.setNewData(ArrayList<PayTypeEntity>().apply {
//                        add(
//                            PayTypeEntity(
//                                R.drawable.iv_pay_qianbao,
//                                "余额支付",
//                                "￥${t?.balance ?: "0.00"}"
//                            )
//                        )
                        add(PayTypeEntity(R.drawable.iv_pay_wechat, "微信支付", ""))
                        add(PayTypeEntity(R.drawable.iv_pay_alipay, "支付宝支付", ""))
                    })
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
    }

    private fun wechatRecharge(
        appid: String?,
        noncestr: String?,
        `package`: String?,
        partnerid: String?,
        prepayid: String?,
        sign: String?,
        timestamp: String?
    ) {
        if (appid == null || noncestr == null || `package` == null || partnerid == null
            || prepayid == null || sign == null || timestamp == null
        ) {
            tipWarn("支付环境异常")
            return
        }
        val msgApi = WXAPIFactory.createWXAPI(context, null)
        msgApi.registerApp(appid)
        val request = PayReq().apply {
            this.appId = appid
            this.nonceStr = noncestr
            this.packageValue = `package`
            this.partnerId = partnerid
            this.prepayId = prepayid
            this.sign = sign
            this.timeStamp = timestamp
        }
        msgApi.sendReq(request)
    }

    class Adapter : BaseQuickAdapter<PayTypeEntity, BaseViewHolder>(R.layout.item_pay_type) {
        var position = -1
        override fun convert(helper: BaseViewHolder, item: PayTypeEntity) {
            helper.getView<SmoothCheckBox>(R.id.check_box)
                .setChecked(position == helper.layoutPosition - headerLayoutCount, true)
            helper.setImageResource(R.id.iv_pay_type, item.drawableInt)
                .setText(R.id.tv_pay_type_name, item.name)
                .setText(R.id.tv_pay_type_money, item.money)
        }

    }
}